<template>
  <div class="wd-wangeditor" style="border: 1px solid #ccc">
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      class="wd-wangeditor-toolbar"
    />
    <Editor
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      style="height: 420px; overflow-y: scroll"
      class="wd-wangeditor-editor"
      @on-created="handleCreated"
    />
    <!-- 图片上传选择弹窗 -->
    <wd-img-picker ref="WdImgPickerRef" @getPickerFiles="getFiles" />
  </div>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { onBeforeUnmount, ref, shallowRef, watch, reactive } from "vue";
import tool from "@/utils/tool";
import WdImgPicker from "@cwd/widgets/wd-image-picker/components/image-picker.vue"; 

const WdImgPickerRef = ref(null);

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  placeholder: {
    type: String,
    default: "请输入内容...",
  },
});
const emit = defineEmits(["update:modelValue"]);

const editorRef = shallowRef(null);
const valueHtml = ref(props.modelValue);

// 双向绑定同步
watch(valueHtml, (val) => {
  emit("update:modelValue", val);
});
watch(
  () => props.modelValue,
  (val) => {
    if (val !== valueHtml.value) {
      valueHtml.value = val;
    }
  }
);

const mode = "default";

const getFiles = (attachList) => {
  if (!editorRef.value) return;
  attachList.forEach((item) => {
    const url = tool.attachUrl(item.att_dir || item.url);
    editorRef.value.dangerouslyInsertHtml(
      `<img src="${url}" style="max-width: 100%;" />`
    );
  });
  WdImgPickerRef.value?.close?.();
};

const uploadImg = () => {
  WdImgPickerRef.value?.open?.();
};

const toolbarConfig = reactive({
  excludeKeys: ["fullScreen"],
  insertKeys: {
    index: 5,
    keys: [],
  },
});

const editorConfig = reactive({
  placeholder: props.placeholder,
  MENU_CONF: {
    uploadImage: {
      maxFileSize: 2 * 1024 * 1024, // 2MB
      fieldName: "file",
      allowedFileTypes: ["image/*"],
      timeout: 10000,
      customBrowseAndUpload: uploadImg,
    },
  },
  customAlert: (msg, type) => {
    console.warn(`[${type}] ${msg}`);
  },
});

const handleCreated = (editor) => {
  editorRef.value = editor;
};

onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy();
    editorRef.value = null;
  }
});
</script>

<style lang="less" scoped>
:deep(.w-e-text-container) {
  .w-e-scroll {
    height: 100%;
  }
}
.wd-wangeditor {
  .wd-wangeditor-toolbar {
    border-bottom: 1px solid #ccc;
  }
}
</style>
